package org.ghost.http.testkit.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.ghost.http.testkit.dto.ConfigInterfaceDTO;
import org.ghost.http.testkit.dto.ResponseVO;
import org.ghost.http.testkit.entity.ConfigInterface;
import org.ghost.http.testkit.entity.ConfigSystem;
import org.ghost.http.testkit.service.IConfigInterfaceService;
import org.ghost.http.testkit.service.IConfigSystemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2018-05-02
 */
@RestController
@RequestMapping("/configInterface")
public class ConfigInterfaceController extends BaseController {
    @Autowired
    private IConfigInterfaceService service;
    @Autowired
    private IConfigSystemService configSystemService;

    /**
     * 实体查询
     */
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public ResponseVO search(@PathVariable Long id) {
        return getFromData(service.selectById(id));
    }

    /**
     * 实体删除
     */
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    public ResponseVO del(@PathVariable Long id) {
        service.deleteById(id);
        return getSuccess();
    }

    /**
     * 实体添加
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseVO add(@RequestBody ConfigInterface entity) {
        service.insert(entity);
        return getSuccess();
    }

    /**
     * 实体修改
     */
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public ResponseVO update(@PathVariable Long id, @RequestBody ConfigInterface entity) {
        entity.setId(id);
        service.updateById(entity);
        return getSuccess();
    }

    /**
     * 实体添加
     */
    @RequestMapping(value = "addOrUpdate", method = RequestMethod.POST)
    public ResponseVO addEntity(ConfigInterface entity) {
        if (entity != null) {
            if (entity.getId() != null && entity.getId() == 0L) {
                entity.setId(null);
            }
            if (entity.getIsDel() == null) {
                entity.setIsDel(0);
            }
            if (entity.getCreatorId() == null) {
                entity.setCreatorId(1L);
            }
            if (entity.getModifierId() == null) {
                entity.setModifierId(1L);
            }
            if (entity.getCreatedAt() == null) {
                entity.setCreatedAt(new Date());
            }
            if (entity.getModifiedAt() == null) {
                entity.setModifiedAt(new Date());
            }

            if (entity.getId() == null) {
                service.insert(entity);
            } else {
                service.updateById(entity);
            }
            return getSuccess();
        }

        return getFailure();
    }

    /**
     * 分页查询
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseVO selectPage(Page<ConfigInterface> page) {
        page = page == null ? new Page<>(1, 10) : page;
        Wrapper<ConfigInterface> wrapper = null;
        if (MapUtils.isNotEmpty(page.getCondition())) {
            wrapper = new EntityWrapper<ConfigInterface>();
            for (Map.Entry<String, Object> item : page.getCondition().entrySet()) {
                if (StringUtils.isNotBlank(item.getKey()) && item.getValue() != null && StringUtils.isNotBlank(item.getValue().toString())) {
                    if (item.getValue() instanceof Long) {
                        wrapper.eq(item.getKey(), item.getValue().toString());
                    } else if (item.getValue() instanceof String) {
                        wrapper.like(item.getKey(), item.getValue().toString());
                    }
                }
            }
        }
        Page<ConfigInterface> pageResult = service.selectPage(page, wrapper);
        if (pageResult != null && CollectionUtils.isNotEmpty(pageResult.getRecords())) {
            List<Long> sysIdList = pageResult.getRecords().stream().filter(Objects::nonNull).map(ConfigInterface::getSysId).filter(Objects::nonNull).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(sysIdList)) {
                Wrapper<ConfigSystem> configSystemWrapper = new EntityWrapper<ConfigSystem>().in("id", sysIdList);
                List<ConfigSystem> configSystemList = configSystemService.selectList(configSystemWrapper);
                if (CollectionUtils.isNotEmpty(configSystemList)) {
                    List<ConfigInterfaceDTO> configInterfaceDTOList = pageResult.getRecords().stream().map(it -> {
                        ConfigInterfaceDTO target = new ConfigInterfaceDTO();
                        BeanUtils.copyProperties(it, target);
                        return target;
                    }).peek(it -> {
                        configSystemList.stream().filter(f -> Objects.equals(f.getId(), it.getSysId())).findFirst().ifPresent((val) -> {
                            it.setSysName(val.getName());
                            it.setSysDesc(val.getDesc());
                        });
                    }).collect(Collectors.toList());

                    Page<ConfigInterfaceDTO> tempPageResult = new Page<ConfigInterfaceDTO>(pageResult.getCurrent(), pageResult.getSize());
                    tempPageResult.setRecords(configInterfaceDTOList);
                    tempPageResult.setTotal(pageResult.getTotal());

                    return getFromData(tempPageResult);
                }
            }
        }

        return getFromData(pageResult);
    }
}
